package com.cdsxlc.common.service.impl;

import com.cdsxlc.common.config.DataSourceConfig;
import com.cdsxlc.common.entity.TableColumns;
import com.cdsxlc.common.service.TableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhang
 */
@Service
public class TableServiceImpl implements TableService {

    private static Logger logger = LoggerFactory.getLogger(TableServiceImpl.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    DataSourceConfig dataSourceConfig;

    @Override
    public List<TableColumns> findTableColumnsByTable(String tableName) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT TABLE_SCHEMA AS tableSchema,TABLE_NAME AS tableName,COLUMN_NAME AS columnName,COLUMN_TYPE AS columnType,")
                .append(" ORDINAL_POSITION AS ordinalPosition,IS_NULLABLE AS notNullFlag,")
                .append("DATA_TYPE AS dataType,NUMERIC_PRECISION as numericPrecision,")
                .append("NUMERIC_SCALE as numericScale,")
                .append(" CHARACTER_MAXIMUM_LENGTH AS columnLength,COLUMN_KEY AS  columnKey,COLUMN_COMMENT AS columnComment")
                .append(" FROM information_schema.columns WHERE table_schema = '")
                .append(dataSourceConfig.getTableSchema())
                .append("' AND table_name = '")
                .append(tableName)
                .append("'");
        logger.info("jdbc getListByTable sql:" + sql.toString());
        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(TableColumns.class));
    }
}
